module KeyDebounce (
    // 50MHz,20ns
    input sys_clk,
    input sys_rst_n,
    // key jitter
    input keyIn,
    // stable key
    output reg stableKey
);

// one beat
reg keyIn_d0;
// two beat
reg keyIn_d1;

// 20ms
reg [19:0] cnt;
parameter [19:0] CNT_MAT=20'd1_000_000;

// count to 20ms
always @(posedge sys_clk,negedge sys_rst_n)begin
    if(!sys_rst_n)cnt<=1'b0;
    if(keyIn_d0!=keyIn_d1)cnt<=CNT_MAT;
    else if(cnt>0)cnt<=cnt-1;
    else cnt<=1'b0;
end

// beat twice
always @(posedge sys_clk,negedge sys_rst_n)begin
    if(!sys_rst_n)begin
        keyIn_d0<=1'b1;
        keyIn_d1<=1'b1;
    end else begin
        keyIn_d0<=keyIn;
        keyIn_d1<=keyIn_d0;
    end
end

// output stable key when press
always @(posedge sys_clk,negedge sys_rst_n)begin
    if(!sys_rst_n)stableKey<=1'b1;
    // elapsed 20ms
    else if(cnt==1)stableKey<=keyIn_d1;
    else stableKey<=stableKey;
end

endmodule
